package com.osce.system.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.doudou.core.container.ListUtil;
import com.doudou.core.throwable.GlobalException;
import com.douodu.excel.status.ImportStatus;
import com.osce.common.annotation.DataScope;
import com.osce.common.core.entity.entity.SysRole;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.entity.vo.SimulatedPatientExcelVo;
import com.osce.common.exception.ServiceException;
import com.osce.common.utils.SecurityUtils;
import com.osce.common.utils.bean.BeanValidators;
import com.osce.interfaces.system.ISimulatedPatientService;
import com.osce.interfaces.system.ISysConfigService;
import com.osce.interfaces.system.ISysRoleService;
import com.osce.interfaces.system.ISysUserService;
import com.osce.system.mapper.SimulatedPatientMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SimulatedPatientServiceImpl implements ISimulatedPatientService {

    private static final Logger log = LoggerFactory.getLogger(SimulatedPatientServiceImpl.class);

    @Resource
    private SimulatedPatientMapper simulatedPatientMapper;
    @Resource
    private ISysConfigService configService;
    @Resource
    private ISysUserService userService;
    @Resource
    protected Validator validator;
    @Resource
    private ISysRoleService roleService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectList(SysUser user) {
        return simulatedPatientMapper.selectSimulatedPatientList(user);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importSimulatedPatient(List<SimulatedPatientExcelVo> userList, Boolean isUpdateSupport, String operName) {
        if (ListUtil.isEmpty(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        SysUser user;
        String password = configService.selectConfigValueByKey("sys.user.initPassword");
        ImportStatus importStatus = new ImportStatus();//提示语句对象
        //查询教师角色
        List<SysRole> simulatedPatientRoles = roleService.selectRoleList(SysRole.builder().roleKey("student").build());
        Long[] simulatedPatientRoleIds = simulatedPatientRoles.stream().map(SysRole::getRoleId).toArray(o-> new Long[simulatedPatientRoles.size()]);
        int index = 1;
        for (SimulatedPatientExcelVo simulatedPatient : userList) {
            try {
                // 验证是否存在这个用户
                SysUser selectUser = userService.selectUserByUserName(simulatedPatient.getUserName());
                if (ObjectUtil.isEmpty(selectUser)) {
                    BeanValidators.validateWithException(validator, simulatedPatient);
                    user = BeanUtil.copyProperties(simulatedPatient, SysUser.class);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    //用户基础数据
                    user.setUserInfo(userService.createUserInfo(simulatedPatient, null, null));
                    user.setRoleIds(simulatedPatientRoleIds);
                    userService.insertUser(user);
                    importStatus.addSuccessMsg(index, "{}", simulatedPatient.getUserName());
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, simulatedPatient);
                    user = BeanUtil.copyProperties(simulatedPatient, SysUser.class);
                    userService.checkUserAllowed(selectUser);
                    userService.checkUserDataScope(selectUser.getUserId());
                    user.setUserId(selectUser.getUserId());
                    user.setUpdateBy(operName);
                    //用户基础数据
                    user.setUserInfo(userService.createUserInfo(simulatedPatient, null, null));
                    userService.updateUser(user);
                    importStatus.addSuccessMsg(index, "{}", simulatedPatient.getUserName());
                } else {
                    throw new GlobalException("账号{}已存在", simulatedPatient.getUserName());
                }
            } catch (Exception e) {
                importStatus.addFailError(index, e);
                log.error("", e);
            } finally {
                index++;
            }
        }
        return importStatus.toHtmlString();
    }

    @Override
    public List<SimulatedPatientExcelVo> toExcelVo(List<SysUser> list) {
        return list.stream().map(u -> {
            SimulatedPatientExcelVo simulatedPatientExcelVo = BeanUtil.copyProperties(u, SimulatedPatientExcelVo.class);
            simulatedPatientExcelVo.setHeight(u.getUserInfo().getHeight());
            simulatedPatientExcelVo.setWeight(u.getUserInfo().getWeight());
            simulatedPatientExcelVo.setNationality(u.getUserInfo().getNationality());
            simulatedPatientExcelVo.setPost(u.getUserInfo().getPost());
            simulatedPatientExcelVo.setMarital(u.getUserInfo().getMarital());
            return simulatedPatientExcelVo;
        }).collect(Collectors.toList());
    }

}
